package repl

import (
	"bufio"
	"fmt"
	"io"
	"strings"
)

// 在StartREPL中使用历史记录
func StartREPL(in io.Reader, out io.Writer) {
	/* scanner := bufio.NewScanner(in)
	env := eval.NewEnvironment()
	history := &History{}

	// 添加内置函数
	env.Set("help", builtinHelp)

	for {
		input, err := readMultiLine(scanner, out)
		if err == io.EOF {
			fmt.Fprintln(out, "\nGoodbye!")
			return
		}

		if input == "" {
			continue
		}

		history.Add(input)

		result, err := eval.Evaluate(input, env)
		if err != nil {
			fmt.Fprintf(out, "Error: %v\n", err)
			continue
		}

		fmt.Fprintf(out, "=> %v\n", result)
	} */
}

// 添加多行输入支持
func ReadMultiLine(scanner *bufio.Scanner, out io.Writer) (string, error) {
	var lines []string

	//判断是不是函数只有函数才能多行输入
	if strings.HasPrefix(scanner.Text(), "func") {
		lines = append(lines, strings.TrimSpace(scanner.Text()))
		fmt.Fprintf(out, "... ")
		for {
			if !scanner.Scan() {
				if err := scanner.Err(); err != nil {
					return "", err
				}
				return "", io.EOF
			}

			line := scanner.Text()
			if line == "" {
				break
			}

			lines = append(lines, strings.TrimSpace(line))
			fmt.Fprintf(out, "... ")
		}
		return strings.Join(lines, "\n"), nil
	}
	return scanner.Text(), nil
}
